import cv2
import numpy as np
import csv
#
# @author brokerxu
# 自动采集图片轮廓坐标脚本代码
#
if __name__ == '__main__':

    # 读取图片
    image_path = './image3.png'  # 替换为您的图片路径
    image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)

    # 检查图片是否具有 alpha 通道
    if image.shape[2] == 4:
        # 分离 alpha 通道
        alpha_channel = image[:, :, 3]

        # 创建一个二值掩模，白色区域标识不透明部分
        ret, mask = cv2.threshold(alpha_channel, 0, 255, cv2.THRESH_BINARY)

        # 找到轮廓
        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        with open('./contours_3.csv', 'w', newline='') as csvfile:
            csv_writer = csv.writer(csvfile)
            # 遍历所有轮廓并打印坐标
            for contour in contours:
                for point in contour:
                    # print("轮廓坐标:", contour)
                    csv_writer.writerow([point[0][0], point[0][1]])
                csv_writer.writerow([])  # 分隔不同轮廓
                # 如果需要的话，可以绘制轮廓
                cv2.drawContours(image, [contour], -1, (0, 255, 0), 1)
    # 在需要时显示图片
    # cv2.imshow('Image', image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
